import {
  wsserver,
} from '/common/config';
import {
  heartCheck,
} from '/utils';

App({
  globalData: {
    reconnectCount: 0,
    onSocketMessage: () => {},
  },

  onLaunch() {
    this.handleWSListener();
  },

  onShow() {
    if (this.globalData.reconnectCount > 0) {
      this.globalData.reconnectCount = 0;
      this.handleConnectSocket();
    }
  },

  // 建立websocket连接监听消息
  handleWSListener() {
    my.onSocketOpen(() => {
      console.log('websocket连接已打开');
      this.globalData.reconnectCount = 0;
      // websocket心跳检测
      heartCheck.reset().start();
    });
    my.onSocketError(() => {
      console.log('websocket连接错误');
      this.wsReConnect();
    });
    my.onSocketClose(() => {
      console.log('webscoket链接已关闭');
      this.wsReConnect();
    });
    my.onSocketMessage((res) => {
      console.log('接收消息', res);
      heartCheck.reset().start();
      if (res.data !== 'alive') {
        const { onSocketMessage } = this.globalData;
        onSocketMessage(res);
      }
    });
  },

  // websocket 连接
  handleConnectSocket() {
    const { data: userId } = my.getStorageSync({
      key: 'userId',
    });
    if (userId) {
      my.connectSocket({
        url: `${wsserver}/websocket/${userId}`,
        success() {
          console.log('websocket连接成功');
        }
      });
    }
  },

  // websocket 重连
  wsReConnect() {
    // 连接断开尝试重连，最多重连10次
    this.globalData.reconnectCount++;
    if (this.globalData.reconnectCount < 10) {
      setTimeout(() => {
        this.handleConnectSocket();
      }, 5000);
    }
  }

});
